import { ref, watch, computed } from "vue";
export function toFixed(num, digits) {
  var numS = num.toString(),
    decPos = numS.indexOf("."),
    substrLength = decPos == -1 ? numS.length : 1 + decPos + digits,
    trimmedResult = numS.substr(0, substrLength),
    finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;

  return parseFloat(finalResult);
}
export const menuList = function () {
  const menu = ref([
    {
      id: 1,
      name: 2,
      price: 12,
      number: 1,
      checked: false,
    },
    {
      id: 2,
      name: 2,
      price: 12,
      number: 1,
      checked: false,
    },
    {
      id: 3,
      name: 2,
      price: 12,
      number: 1,
      checked: false,
    },
  ]);
  const check_all = ref(false);
  const total = computed(() => {
    return menu.value
      .map((res) => {
        if (res.checked === true) {
          return toFixed(res.price * res.number, 2);
        } else {
          return 0;
        }
      })
      .reduce((prev, next) => {
        return prev + next;
      }, 0);
  });
  const add = function (id) {
    let obj = menu.value.find((res) => {
      return res.id === id;
    });
    obj.number = obj.number + 1;
  };
  const reduce = function (id) {
    let obj = menu.value.find((res) => {
      return res.id === id;
    });
    if (obj.number === 0) return;
    obj.number = obj.number - 1;
  };
  const setMenu = function (data) {
    menu.value = data;
  };
  watch(
    menu,
    function (o, n) {
      console.log(o, n);
    },
    { immediate: true }
  );
  watch(check_all, function (n, o) {
    console.log(n, o);
    let arr = JSON.parse(JSON.stringify(menu.value));

    if (n) {
      let result = arr.map((res) => {
        res.checked = n;
        return res;
      });
      setMenu(result);
    } else {
      let result = arr.map((res) => {
        res.checked = n;
        return res;
      });
      setMenu(result);
    }
  });

  return {
    menu,
    setMenu,
    total,
    add,
    reduce,
    check_all,
  };
};
